package com.itheima.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author Gareth Cao
 * @date 2022/4/26 11:24
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<Object> exceptionHandler1(SQLIntegrityConstraintViolationException ex) {
        //获取异常信息
        String message = ex.getMessage(); //Duplicate entry 'caoruifeng' for key 'idx_username'
        //解析异常信息获取关键字段username
        String username = message.split(" ")[2];
        return R.error(username + "该账号已经存在,请重新输入要新增的用户名");
    }

    @ExceptionHandler(DeleteCategoryException.class)
    public R<Object> exceptionHandler2(DeleteCategoryException ex) {
        //获取异常信息
        String message = ex.getMessage();
        return R.error(message);
    }

    @ExceptionHandler(DeleteSetmealException.class)
    public R<Object> exceptionHandler3(DeleteSetmealException ex) {
        //获取异常信息
        String message = ex.getMessage();
        return R.error(message);
    }
}
